package com.yami.shop.api.controller.app;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.api.config.DistanceUtils;
import com.yami.shop.bean.app.dto.UserDto;
import com.yami.shop.bean.dto.UserCardDto;
import com.yami.shop.bean.dto.UserViewDto;
import com.yami.shop.bean.model.UnlockRecord;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.model.UserLikeRecord;
import com.yami.shop.bean.model.ViewUserRecord;
import com.yami.shop.dao.DistanceMapper;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.UnlockRecordService;
import com.yami.shop.service.UserLikeRecordService;
import com.yami.shop.service.UserService;
import com.yami.shop.service.ViewUserRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/p/main")
@Api(tags = "APP首页")
@AllArgsConstructor
// @CrossOrigin(origins = "http://127.0.0.1")
public class MainController {

    private final UserService userService;

    private final MapperFacade mapperFacade;

    private final ViewUserRecordService viewUserRecordService;
    private final UnlockRecordService unlockRecordService;
    private final UserLikeRecordService userLikeRecordService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DistanceMapper distanceMapper;
    /**
     * 获取推荐流
     */
    @GetMapping
    @ApiOperation(value = "获取推荐流", notes = "根据不同用户返回不同推荐流")
    public ResponseEntity<List<UserCardDto>> getUsers() throws IOException {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        List<UserCardDto> dtos = userService.getRecommendUsers(user, 0);
        for (UserCardDto dto : dtos) {

            //是否已解锁该用户
            if (unlockRecordService.isUnlocked(userId, dto.getUserId())) {
                dto.setIsUnlocked(1);
            } else {
                dto.setIsUnlocked(0);
            }

            //是否已喜欢该用户
            if (userLikeRecordService.isLiked(userId, dto.getUserId())) {
                dto.setIsLiked(1);
            } else {
                dto.setIsLiked(0);
            }
        }
        return ResponseEntity.ok(dtos);
    }

    /**
     * 获取距离优先推荐
     */
    @GetMapping("/dis")
    @ApiOperation(value = "距离优先", notes = "按照距离排序")
    public ResponseEntity<List<UserCardDto>> getDistUser() throws IOException {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        String sex = user.getSex();

        if (sex.equals("M")){
            List<UserCardDto> dtos =  userService.getDisUserSex(user.getLng(),user.getLat());
            for (int i = 0;i<dtos.size();i++) {

                //是否已解锁该用户
                if (unlockRecordService.isUnlocked(userId, dtos.get(i).getUserId())) {
                    dtos.get(i).setIsUnlocked(1);
                } else {
                    dtos.get(i).setIsUnlocked(0);
                }

                //是否已喜欢该用户
                if (userLikeRecordService.isLiked(userId, dtos.get(i).getUserId())) {
                    dtos.get(i).setIsLiked(1);
                } else {
                    dtos.get(i).setIsLiked(0);
                }

                if(dtos.get(i).getUserId().equals(userId)){
                    dtos.remove(i);
                    i--;
                }

            }
            return ResponseEntity.ok(dtos);
        }else {
            List<UserCardDto> dtos =  userService.getDisUser(user.getLng(),user.getLat());
            for (int i = 0;i<dtos.size();i++) {

                //是否已解锁该用户
                if (unlockRecordService.isUnlocked(userId, dtos.get(i).getUserId())) {
                    dtos.get(i).setIsUnlocked(1);
                } else {
                    dtos.get(i).setIsUnlocked(0);
                }

                //是否已喜欢该用户
                if (userLikeRecordService.isLiked(userId, dtos.get(i).getUserId())) {
                    dtos.get(i).setIsLiked(1);
                } else {
                    dtos.get(i).setIsLiked(0);
                }

                if(dtos.get(i).getUserId().equals(userId)){
                    dtos.remove(i);
                    i--;
                }

            }
            return ResponseEntity.ok(dtos);
        }
    }

    /**
     * 获取新人优先推荐
     */
    @GetMapping("/news")
    @ApiOperation(value = "新人优先", notes = "按最新注册用户排序")
    public ResponseEntity<List<UserCardDto>> getNewUser() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        String sex = user.getSex();
        List<UserCardDto> dtos =  userService.getNewUser(user.getUserId(),sex);
        Date now = new Date();
        for (UserCardDto dto : dtos){
            long betweenDay = DateUtil.between(now, dto.getUserRegtime(), DateUnit.DAY);
            dto.setDayDis(betweenDay);

            if (user.getLng() != null && user.getLat() != null && dto.getLng() != null && dto.getLat()!= null){
                dto.setDistance(DistanceUtils.getDistance(user.getLng(),user.getLat(),dto.getLng(),dto.getLat()));
            }

            //是否已解锁该用户
            if (unlockRecordService.isUnlocked(userId, dto.getUserId())) {
                dto.setIsUnlocked(1);
            } else {
                dto.setIsUnlocked(0);
            }

            //是否已喜欢该用户
            if (userLikeRecordService.isLiked(userId, dto.getUserId())) {
                dto.setIsLiked(1);
            } else {
                dto.setIsLiked(0);
            }

        }

        return ResponseEntity.ok(dtos);
    }

    /**
     * 在线优先推荐接口
     */
    @GetMapping("/onl")
    @ApiOperation(value = "在线优先", notes = "按照是否在线排序")
    public ResponseEntity<List<UserCardDto>> getOnlUser() throws IOException {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        String sex = user.getSex();
        List<UserCardDto> dtos =  userService.getOnlUser(user.getUserId(),sex);
        for (UserCardDto dto : dtos) {
            if (user.getLng() != null && user.getLat() != null && dto.getLng() != null && dto.getLat()!= null){
                dto.setDistance(DistanceUtils.getDistance(user.getLng(),user.getLat(),dto.getLng(),dto.getLat()));
            }
            //是否已解锁该用户
            if (unlockRecordService.isUnlocked(userId, dto.getUserId())) {
                dto.setIsUnlocked(1);
            } else {
                dto.setIsUnlocked(0);
            }

            //是否已喜欢该用户
            if (userLikeRecordService.isLiked(userId, dto.getUserId())) {
                dto.setIsLiked(1);
            } else {
                dto.setIsLiked(0);
            }
        }

        return ResponseEntity.ok(dtos);
    }

    /**
     * 地区选择推荐
     */
    @GetMapping("/loc")
    @ApiOperation(value = "按地区选择推荐", notes = "如果prov和city值都为fj，则筛选附近30km内的用户")
    public ResponseEntity<List<UserCardDto>> getLocUser(String prov,String city) throws IOException {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        if(prov.equals("fj") && city.equals("fj")){
            String sex = user.getSex();
            if(sex.equals("M")){
                List<UserCardDto> dtos = distanceMapper.queryNeaUsersSex(user.getLng(), user.getLat());
                for (int i = 0;i<dtos.size();i++) {
                    //是否已解锁该用户
                    if (unlockRecordService.isUnlocked(userId, dtos.get(i).getUserId())) {
                        dtos.get(i).setIsUnlocked(1);
                    } else {
                        dtos.get(i).setIsUnlocked(0);
                    }

                    //是否已喜欢该用户
                    if (userLikeRecordService.isLiked(userId, dtos.get(i).getUserId())) {
                        dtos.get(i).setIsLiked(1);
                    } else {
                        dtos.get(i).setIsLiked(0);
                    }

                    if(dtos.get(i).getUserId().equals(userId)){
                        dtos.remove(i);
                        i--;
                    }

                }
                return ResponseEntity.ok(dtos);
            }else {
                List<UserCardDto> dtos = distanceMapper.queryNeaUsers(user.getLng(), user.getLat());
                for (int i = 0;i<dtos.size();i++) {
                    //是否已解锁该用户
                    if (unlockRecordService.isUnlocked(userId, dtos.get(i).getUserId())) {
                        dtos.get(i).setIsUnlocked(1);
                    } else {
                        dtos.get(i).setIsUnlocked(0);
                    }

                    //是否已喜欢该用户
                    if (userLikeRecordService.isLiked(userId, dtos.get(i).getUserId())) {
                        dtos.get(i).setIsLiked(1);
                    } else {
                        dtos.get(i).setIsLiked(0);
                    }

                    if(dtos.get(i).getUserId().equals(userId)){
                        dtos.remove(i);
                        i--;
                    }

                }
                return ResponseEntity.ok(dtos);

            }


        }else {
            String sex = user.getSex();
            List<UserCardDto> dtos =  userService.getLocUser(user.getUserId(),prov,city,sex);
            for (UserCardDto dto : dtos) {
                if (user.getLng() != null && user.getLat() != null && dto.getLng() != null && dto.getLat()!= null){
                    dto.setDistance(DistanceUtils.getDistance(user.getLng(),user.getLat(),dto.getLng(),dto.getLat()));
                }

                //是否已解锁该用户
                if (unlockRecordService.isUnlocked(userId, dto.getUserId())) {
                    dto.setIsUnlocked(1);
                } else {
                    dto.setIsUnlocked(0);
                }

                //是否已喜欢该用户
                if (userLikeRecordService.isLiked(userId, dto.getUserId())) {
                    dto.setIsLiked(1);
                } else {
                    dto.setIsLiked(0);
                }

            }
            return ResponseEntity.ok(dtos);
        }

    }

    /**
     * vip男生接口
     */
    @GetMapping("/vipMale")
    @ApiOperation(value = "vip男生", notes = "vip男生")
    public ResponseEntity<List<UserCardDto>> getVipMale() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        List<UserCardDto> dtos =  userService.getVipMale(user.getUserId());
        for (UserCardDto dto : dtos){
            if (user.getLng() != null && user.getLat() != null && dto.getLng() != null && dto.getLat()!= null){
                dto.setDistance(DistanceUtils.getDistance(user.getLng(),user.getLat(),dto.getLng(),dto.getLat()));
            }

            //是否已解锁该用户
            if (unlockRecordService.isUnlocked(userId, dto.getUserId())) {
                dto.setIsUnlocked(1);
            } else {
                dto.setIsUnlocked(0);
            }

            //是否已喜欢该用户
            if (userLikeRecordService.isLiked(userId, dto.getUserId())) {
                dto.setIsLiked(1);
            } else {
                dto.setIsLiked(0);
            }
        }

        return ResponseEntity.ok(dtos);
    }

    /**
     * vip女生接口
     */
    @GetMapping("/vipFemale")
    @ApiOperation(value = "vip女生", notes = "vip女生")
    public ResponseEntity<List<UserCardDto>> getVipFemale() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        List<UserCardDto> dtos =  userService.getVipFemale(user.getUserId());
        for (UserCardDto dto : dtos){
            if (user.getLng() != null && user.getLat() != null && dto.getLng() != null && dto.getLat()!= null){
                dto.setDistance(DistanceUtils.getDistance(user.getLng(),user.getLat(),dto.getLng(),dto.getLat()));
            }
            dto.setIsUnlocked(0);

            //是否已喜欢该用户
            if (userLikeRecordService.isLiked(userId, dto.getUserId())) {
                dto.setIsLiked(1);
            } else {
                dto.setIsLiked(0);
            }
        }
        return ResponseEntity.ok(dtos);
    }

    @GetMapping("/userInfo/{id}")
    @ApiOperation(value = "某人查看用户详情", notes = "点击查看别人的详情")
    public ResponseEntity<UserViewDto> userInfo(@PathVariable("id") String lookUid){
        String userId = SecurityUtils.getUser().getUserId();
        User lookUser = userService.getById(lookUid);
        UserViewDto userViewDto = mapperFacade.map(lookUser, UserViewDto.class);

        userViewDto.setPic(lookUser.getPic());
        //是否已解锁该用户
        if (unlockRecordService.isUnlocked(userId, lookUid)) {
            userViewDto.setIsUnlocked(1);
        } else {
            userViewDto.setIsUnlocked(0);
        }

        //是否已喜欢该用户
        if (userLikeRecordService.isLiked(userId, lookUid)) {
            userViewDto.setIsLiked(1);
        } else {
            userViewDto.setIsLiked(0);
        }

        ViewUserRecord v = new ViewUserRecord();
        v.setFromUserId(userId);
        v.setLookedUserId(lookUid);
        v.setCreateTime(new Date());
        String user1 = new String();
        user1 = v.getFromUserId();
        String user2 = new String();
        user2 = v.getLookedUserId();
        if(userMapper.queryChaKan(user1,user2)==0){//重复查看同一个人不会重复添加查看记录
            viewUserRecordService.save(v);
        }



        return ResponseEntity.ok(userViewDto);
    }
}
